package com.awesome.socketdemo.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.security.Provider;
import java.util.UUID;

/**
 * Author: zhangjingfang
 * Email:zhangjingfang@jeejio.com
 * Date: 2021/7/15 10:52 下午
 * Description:类描述
 */
public class UDPSimpleProvider {
    public static void main(String[] args) throws IOException {
        System.out.println("UDPProvider Started.");
        // 作为接收者，指定一个端口用于数据接收
        DatagramSocket ds = new DatagramSocket(20000);

        // 构建接收实体
        final byte[] buf = new byte[512];
        DatagramPacket receiverPack = new DatagramPacket(buf, buf.length);

        // 接收
        ds.receive(receiverPack);

        // 打印接收到的信息与发送者的信息
        // 发送者的IP地址
        String ip = receiverPack.getAddress().getHostAddress();
        int port = receiverPack.getPort();
        int dataLen = receiverPack.getLength();
        String data = new String(receiverPack.getData(), 0, dataLen);
        System.out.println("UDPProvider receive from ip:" + ip + "\tport:" + port + "\tdata:" + data);

        // 构建一份回送数据
        String responseData = "Receive data with len:" + dataLen;
        byte[] responseDataBytes = responseData.getBytes();
        // 直接根据发送者构建一份回送信息
        DatagramPacket responsePacket = new DatagramPacket(responseDataBytes, responseDataBytes.length,
                receiverPack.getAddress(), receiverPack.getPort());
        ds.send(responsePacket);

        // 完成
        System.out.println("UDPProvider Finished.");
        ds.close();
    }

} 